<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 聊天消息列表
const messages = ref([
  {
    id: 1,
    content: '您好！我是AI购物助手，请问您想买什么商品呢？您可以告诉我商品类型、预算、品牌偏好等信息，我会为您推荐性价比最高的商品。',
    sender: 'ai',
    time: '09:30'
  }
])

// 新消息输入框
const newMessage = ref('')
const messageInput = ref(null)
const messagesContainer = ref(null)
const isTyping = ref(false)

// 模拟商品数据库
const mockProducts = ref([
  {
    id: 1,
    name: '小米13 Pro 智能手机',
    price: 4999,
    originalPrice: 5999,
    rating: 4.8,
    sales: 12345,
    category: '手机',
    brand: '小米',
    specs: '骁龙8 Gen 2处理器，12GB内存，256GB存储，徕卡相机',
    description: '高性能旗舰手机，徕卡专业影像系统',
    image: 'https://img.alicdn.com/imgextra/i1/O1CN01X0FzNQ27YtU4K2bVQ_!!6000000007990-0-picassoopen.jpg'
  },
  {
    id: 2,
    name: '华为Mate 60 Pro',
    price: 6999,
    originalPrice: 7999,
    rating: 4.9,
    sales: 23456,
    category: '手机',
    brand: '华为',
    specs: '麒麟9000S处理器，12GB内存，512GB存储，XMAGE影像',
    description: '国产高端旗舰，自主研发芯片',
    image: 'https://img.alicdn.com/imgextra/i2/O1CN01z8X2ZQ1vJ1z6Z8X2Z_!!6000000006227-0-picassoopen.jpg'
  },
  {
    id: 3,
    name: 'iPhone 15 Pro Max',
    price: 9999,
    originalPrice: 10999,
    rating: 4.7,
    sales: 34567,
    category: '手机',
    brand: '苹果',
    specs: 'A17 Pro处理器，8GB内存，256GB存储，钛金属机身',
    description: '苹果最新旗舰，钛金属设计，A17 Pro芯片',
    image: 'https://img.alicdn.com/imgextra/i3/O1CN013vR93t1eZ2wY7Y6qL_!!6000000006001-0-picassoopen.jpg'
  },
  {
    id: 4,
    name: '索尼WH-1000XM5 耳机',
    price: 2999,
    originalPrice: 3499,
    rating: 4.9,
    sales: 8923,
    category: '耳机',
    brand: '索尼',
    specs: '主动降噪，30小时续航，触控操作',
    description: '索尼顶级降噪耳机，音质出色',
    image: 'https://img.alicdn.com/imgextra/i4/O1CN01X0FzNQ27YtU4K2bVQ_!!6000000007990-0-picassoopen.jpg'
  },
  {
    id: 5,
    name: 'AirPods Pro 2',
    price: 1899,
    originalPrice: 1999,
    rating: 4.6,
    sales: 45678,
    category: '耳机',
    brand: '苹果',
    specs: '主动降噪，自适应通透模式，H2芯片',
    description: '苹果最新款降噪耳机，支持MagSafe充电',
    image: 'https://img.alicdn.com/imgextra/i1/O1CN01e0Z4fO1yG7g7Q1Zfo_!!6000000006889-0-picassoopen.jpg'
  },
  {
    id: 6,
    name: '戴森V15 Detect 吸尘器',
    price: 5990,
    originalPrice: 6990,
    rating: 4.8,
    sales: 5678,
    category: '家电',
    brand: '戴森',
    specs: '激光探测微尘，智能调节吸力，60分钟续航',
    description: '戴森顶级吸尘器，激光显尘技术',
    image: 'https://img.alicdn.com/imgextra/i2/O1CN01z8X2ZQ1vJ1z6Z8X2Z_!!6000000006227-0-picassoopen.jpg'
  },
  {
    id: 7,
    name: '小米空气净化器4 Pro',
    price: 1699,
    originalPrice: 1999,
    rating: 4.7,
    sales: 12345,
    category: '家电',
    brand: '小米',
    specs: 'OLED触控屏，H13级HEPA滤网，600m³/h CADR',
    description: '高效空气净化，智能控制',
    image: 'https://img.alicdn.com/imgextra/i3/O1CN013vR93t1eZ2wY7Y6qL_!!6000000006001-0-picassoopen.jpg'
  },
  {
    id: 8,
    name: '格力空调 变频冷暖 1.5匹',
    price: 2699,
    originalPrice: 3299,
    rating: 4.6,
    sales: 8923,
    category: '家电',
    brand: '格力',
    specs: '变频压缩机，一级能效，智能WiFi',
    description: '格力经典款空调，省电耐用',
    image: 'https://img.alicdn.com/imgextra/i4/O1CN01X0FzNQ27YtU4K2bVQ_!!6000000007990-0-picassoopen.jpg'
  }
])

// 模拟回复选项
const quickReplies = ref([
  '推荐一款性价比高的手机',
  '我想买个耳机，预算2000元以内',
  '有什么好的家电推荐吗',
  '推荐一些小米品牌的产品'
])

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 分析用户意图
const analyzeUserIntent = (message) => {
  const lowerMessage = message.toLowerCase()
  const intent = {
    category: null,
    budget: null,
    brand: null,
    keywords: []
  }
  
  // 识别商品类别
  const categories = ['手机', '耳机', '家电', '电脑', '相机', '手表', '平板', '音响']
  for (const category of categories) {
    if (lowerMessage.includes(category)) {
      intent.category = category
      break
    }
  }
  
  // 识别预算
  const budgetRegex = /(\d+)元以内|预算(\d+)元|不超过(\d+)元/;
  const budgetMatch = lowerMessage.match(budgetRegex);
  if (budgetMatch) {
    intent.budget = parseInt(budgetMatch[1] || budgetMatch[2] || budgetMatch[3]);
  }
  
  // 识别品牌
  const brands = ['苹果', '华为', '小米', '索尼', '戴森', '格力', '三星', 'OPPO', 'vivo']
  for (const brand of brands) {
    if (lowerMessage.includes(brand)) {
      intent.brand = brand
      break
    }
  }
  
  // 提取关键词
  const keywords = ['性价比', '好用', '耐用', '新款', '高端', '入门', '学生', '游戏', '拍照']
  for (const keyword of keywords) {
    if (lowerMessage.includes(keyword)) {
      intent.keywords.push(keyword)
    }
  }
  
  return intent
}

// 计算商品性价比分数
const calculateValueScore = (product, intent) => {
  let score = 0
  
  // 基础评分：折扣率、评分、销量权重
  const discountRate = product.originalPrice > 0 ? product.price / product.originalPrice : 1
  score += (1 - discountRate) * 30 // 折扣力度占30分
  score += product.rating * 10 // 评分占40分 (4.8 * 10 = 48)
  score += Math.min(product.sales / 10000, 1) * 20 // 销量占20分
  
  // 根据用户意图调整分数
  if (intent.category && product.category === intent.category) {
    score += 10
  }
  
  if (intent.brand && product.brand === intent.brand) {
    score += 10
  }
  
  if (intent.budget && product.price <= intent.budget) {
    score += 5
    // 价格越接近预算上限但不超过，分数越高
    const priceRatio = product.price / intent.budget
    score += priceRatio * 5
  }
  
  // 关键词匹配加分
  if (intent.keywords.includes('性价比') && discountRate < 0.9) {
    score += 15
  }
  
  if (intent.keywords.includes('高端') && product.price > 3000) {
    score += 10
  }
  
  if (intent.keywords.includes('入门') && product.price < 1000) {
    score += 10
  }
  
  return score
}

// 推荐商品
const recommendProducts = (intent) => {
  // 根据意图过滤商品
  let filteredProducts = [...mockProducts.value]
  
  if (intent.category) {
    filteredProducts = filteredProducts.filter(p => p.category === intent.category)
  }
  
  if (intent.brand) {
    filteredProducts = filteredProducts.filter(p => p.brand === intent.brand)
  }
  
  if (intent.budget) {
    filteredProducts = filteredProducts.filter(p => p.price <= intent.budget)
  }
  
  // 计算每个商品的性价比分数
  const productsWithScore = filteredProducts.map(product => ({
    ...product,
    valueScore: calculateValueScore(product, intent)
  }))
  
  // 按分数排序
  productsWithScore.sort((a, b) => b.valueScore - a.valueScore)
  
  // 返回前3个推荐
  return productsWithScore.slice(0, 3)
}

// 生成AI回复
const generateAIResponse = (userMessage) => {
  const intent = analyzeUserIntent(userMessage)
  const recommendedProducts = recommendProducts(intent)
  
  let response = ''
  
  if (recommendedProducts.length > 0) {
    response = '根据您的需求，我为您推荐以下性价比最高的商品：\n\n'
    
    recommendedProducts.forEach((product, index) => {
      const discount = product.originalPrice > 0 
        ? Math.round((1 - product.price / product.originalPrice) * 100) 
        : 0
      
      response += `${index + 1}. ${product.name}\n`
      response += `- 品牌：${product.brand}\n`
      response += `- 价格：¥${product.price} ${discount > 0 ? `(原价¥${product.originalPrice}，省${discount}%)` : ''}\n`
      response += `- 评分：${product.rating}分 | 销量：${product.sales}\n`
      response += `- 特点：${product.description}\n\n`
    })
    
    response += '您对这些推荐有什么看法？需要了解更多信息吗？'
  } else {
    response = '很抱歉，我没有找到符合您要求的商品。请尝试调整您的搜索条件，比如放宽预算范围或者更改品牌要求。'
  }
  
  return response
}

// 发送消息
const sendMessage = () => {
  if (!newMessage.value.trim()) return
  
  const message = {
    id: Date.now(),
    content: newMessage.value.trim(),
    sender: 'user',
    time: getCurrentTime()
  }
  
  messages.value.push(message)
  newMessage.value = ''
  
  // 滚动到底部
  scrollToBottom()
  
  // 模拟AI回复
  setTimeout(() => {
    simulateAIReply()
  }, 1000)
}

// 模拟AI回复
const simulateAIReply = () => {
  isTyping.value = true
  
  setTimeout(() => {
    const lastUserMessage = messages.value.filter(m => m.sender === 'user').pop()
    const aiResponse = generateAIResponse(lastUserMessage.content)
    
    messages.value.push({
      id: Date.now() + 1,
      content: aiResponse,
      sender: 'ai',
      time: getCurrentTime()
    })
    
    isTyping.value = false
    scrollToBottom()
  }, 2000)
}

// 点击快捷回复
const useQuickReply = (reply) => {
  newMessage.value = reply
  sendMessage()
}

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  }, 100)
}

// 监听键盘事件
const handleKeyPress = (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    sendMessage()
  }
}

// 返回首页
const goBackToHome = () => {
  router.push('/home')
}

onMounted(() => {
  scrollToBottom()
  // 自动获取焦点
  if (messageInput.value) {
    messageInput.value.focus()
  }
})
</script>

<template>
  <div class="ai-chat-view">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <button class="back-btn" @click="goBackToHome">
        <span class="back-icon">←</span>
      </button>
      <div class="ai-info">
        <img src="https://img.alicdn.com/imgextra/i1/O1CN01Z7X5Xs1vX5Xs1vX5_!!6000000006453-2-tps-48-48.png" alt="AI助手头像" class="ai-avatar" />
        <div class="ai-name">AI购物助手</div>
        <div class="online-status">
          <span class="online-indicator"></span>
          <span class="status-text">在线</span>
        </div>
      </div>
      <button class="more-btn">
        <span class="more-icon">⋮</span>
      </button>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="message in messages" :key="message.id" class="message-item" :class="message.sender">
        <div class="message-content">
          {{ message.content }}
        </div>
        <div class="message-time">{{ message.time }}</div>
      </div>
      
      <!-- 正在输入提示 -->
      <div v-if="isTyping" class="typing-indicator">
        <span class="typing-dot"></span>
        <span class="typing-dot"></span>
        <span class="typing-dot"></span>
      </div>
    </div>

    <!-- 快捷回复区域 -->
    <div class="quick-replies">
      <button 
        v-for="(reply, index) in quickReplies" 
        :key="index" 
        class="quick-reply-btn"
        @click="useQuickReply(reply)"
      >
        {{ reply }}
      </button>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-area">
      <textarea 
        ref="messageInput"
        v-model="newMessage" 
        class="message-input" 
        placeholder="请输入您想买的商品信息，例如：推荐一款性价比高的手机，预算3000元以内..."
        rows="1"
        @keypress="handleKeyPress"
      ></textarea>
      <button class="send-btn" @click="sendMessage" :disabled="!newMessage.trim()">
        发送
      </button>
    </div>
  </div>
</template>

<style scoped>
.ai-chat-view {
  background-color: #f5f5f5;
  height: 100vh;
  display: flex;
  flex-direction: column;
  width: 100%;
}

/* 聊天头部样式 */
.chat-header {
  background-color: #4a90e2;
  padding: 15px 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  border-bottom: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 5px;
  color: #fff;
}

.ai-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
}

.ai-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  background-color: #fff;
  padding: 2px;
}

.ai-name {
  font-size: 16px;
  font-weight: 500;
  color: #fff;
}

.online-status {
  display: flex;
  align-items: center;
  gap: 5px;
}

.online-indicator {
  width: 8px;
  height: 8px;
  background-color: #52c41a;
  border-radius: 50%;
}

.status-text {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

.more-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 5px;
  color: #fff;
}

/* 聊天消息区域 */
.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message-item {
  display: flex;
  flex-direction: column;
  max-width: 80%;
}

.message-item.ai {
  align-self: flex-start;
}

.message-item.user {
  align-self: flex-end;
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.6;
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-line;
}

.message-item.ai .message-content {
  background-color: #fff;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
}

.message-item.user .message-content {
  background-color: #4a90e2;
  color: #fff;
  border-bottom-right-radius: 4px;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
  align-self: flex-end;
}

.message-item.ai .message-time {
  align-self: flex-start;
}

/* 正在输入提示 */
.typing-indicator {
  align-self: flex-start;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 18px;
  border-bottom-left-radius: 4px;
  display: flex;
  gap: 5px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
}

.typing-dot {
  width: 8px;
  height: 8px;
  background-color: #999;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-dot:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 快捷回复区域 */
.quick-replies {
  background-color: #fff;
  padding: 15px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  gap: 10px;
  overflow-x: auto;
  flex-wrap: nowrap;
}

.quick-reply-btn {
  padding: 8px 16px;
  background-color: #f5f5f5;
  border: 1px solid #e0e0e0;
  border-radius: 18px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
}

.quick-reply-btn:hover {
  background-color: #e3f2fd;
  border-color: #4a90e2;
  color: #4a90e2;
}

/* 输入区域 */
.chat-input-area {
  background-color: #fff;
  padding: 15px 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  align-items: flex-end;
  gap: 10px;
}

.message-input {
  flex: 1;
  min-height: 36px;
  max-height: 120px;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 18px;
  font-size: 14px;
  resize: none;
  outline: none;
  transition: border-color 0.3s;
  font-family: inherit;
}

.message-input:focus {
  border-color: #4a90e2;
}

.send-btn {
  padding: 8px 20px;
  background-color: #4a90e2;
  color: #fff;
  border: none;
  border-radius: 18px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.send-btn:hover:not(:disabled) {
  background-color: #357abd;
}

.send-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-item {
    max-width: 85%;
  }
  
  .quick-replies {
    padding: 10px 15px;
  }
  
  .chat-input-area {
    padding: 10px 15px;
  }
}
</style>